<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['sl:leaverecord:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-close"
          size="mini"
          @click="handleClose"
        >关闭</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="leaverecordList" @selection-change="handleSelectionChange">
      <el-table-column type="index" width="55" align="center" />
      <el-table-column label="用户" align="center" prop="userNick" />
      <el-table-column label="请假类型" align="center" prop="vacation.vacationName" />
      <el-table-column label="开始日期" align="center" prop="dateStart" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.dateStart, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束日期" align="center" prop="dateEnd" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.dateEnd, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="请假天数" align="center" prop="leaveDay" />
      <el-table-column label="假期薪资" align="center" prop="vacationPay" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['sl:leaverecord:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['sl:leaverecord:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 添加或修改请假记录对话框 -->
      <el-dialog :title="title" :visible.sync="open" width="720px" append-to-body>
        <el-form ref="form" :model="form" :rules="rules" label-width="100px">
          <el-form-item label="假别" prop="vacationId">
            <el-select v-model="form.vacationId" @change="handleCountVacationPay" style="width:100%"  placeholder="请选择假别">
              <el-option
                v-for="item in vacationOptions"
                :key="item.vacationId"
                :label="item.vacationName"
                :value="item.vacationId"
                :disabled="item.status == 1"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="请假日期" prop="daterangeTime">
            <el-date-picker
              v-model="daterangeTime"
              type="datetimerange"
              value-format="yyyy-MM-dd HH:mm:ss"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              @change="handleSetDate"
              :picker-options="pickerOptions"
              >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="请假天数" prop="leaveDay">
            <el-input v-model="form.leaveDay" class="def-input-number" @change="handleCountVacationPay" type="number" placeholder="请输入请假天数" />
          </el-form-item>
          <el-form-item label="假期薪资" prop="vacationPay">
            <el-input v-model="form.vacationPay" :disabled="true" class="def-input-number" type="number" placeholder="自动计算" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>
  </div>
</template>

<script>
import { listLeaverecord, getLeaverecord, delLeaverecord, addLeaverecord, updateLeaverecord } from "@/api/sl/leaverecord";
import { getMonthofc } from "@/api/sl/monthofc";

export default {
  name: "Leaverecord",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 请假记录表格数据
      leaverecordList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        ofcmpayId: null,
        userName: null,
        userNick: null,
        ofcmpayYear: null,
        ofcmpayMonth: null,
        leaveDate: null,
        dateStart: null,
        dateEnd: null,
        leaveDay: null,
        vacationId: null,
        vacationPay: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        vacationId: [
          { required: true, message: "请假类型不能为空", trigger: "change" }
        ],
        daterangeTime: [
          { required: true, validator: this.validateRange() , trigger: "change" }
        ],
        leaveDay: [
          { required: true, message: "请假天数不能为空", trigger: "change" }
        ],
        vacationPay: [
          { required: true, message: "假期薪资不能为空", trigger: "change" }
        ],

      },
      //时间范围
      daterangeTime: [],
      vacationOptions:[],
      //工资人员信息
      monthofcInfo: {
        ofcmpayId:null,
      },
      pickerOptions:{},
    };
  },
  created() {
    const mpayId = this.$route.params && this.$route.params.mpayId;
    if (mpayId) {
      this.queryParams.ofcmpayId = mpayId;
      this.fnGetMonthofc(mpayId);
      this.getList();
    }
  },
  methods: {
    /** 查询请假记录列表 */
    getList() {
      this.loading = true;
      listLeaverecord(this.queryParams).then(response => {
        this.leaverecordList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    //获取工资中的人员日期信息
    fnGetMonthofc(mpayId){
      getMonthofc(mpayId).then(response => {
        this.monthofcInfo = response.data;
        //设置时间选择范围为当月
        let year = this.monthofcInfo.ofcmpayYear;
        let month = this.monthofcInfo.ofcmpayMonth;
        this.pickerOptions.disabledDate = function(obj){
            // 起始时间
            let dateBegin = new Date(year,month-1,'01');
            let timeBegin = dateBegin.getTime();
            // 当前时间
            let currentTime = obj.getTime();
            // 结束时间
            let dateEnd = new Date(year,month,'01');
            let timeEnd = dateEnd.getTime()-3600 * 1000 * 24;
            // 时间选择范围
            return currentTime > timeEnd || currentTime<timeBegin;
        };
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        leaveRecordId: null,
        ofcmpayId: null,
        userName: null,
        userNick: null,
        ofcmpayYear: null,
        ofcmpayMonth: null,
        leaveDate: null,
        dateStart: null,
        dateEnd: null,
        leaveDay: null,
        vacationId: null,
        vacationPay: null
      };
      this.daterangeTime = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.leaveRecordId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      if(this.monthofcInfo ==null || this.monthofcInfo.ofcmpayId==null||this.monthofcInfo.ofcmpayId==''){
        this.$modal.msgError("用户信息错误，请重新打开页面。");
        return false;
      }
      getLeaverecord().then(response => {
        this.vacationOptions = response.vacations;
        this.open = true;
        this.title = "添加请假记录";
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const leaveRecordId = row.leaveRecordId || this.ids
      getLeaverecord(leaveRecordId).then(response => {
        this.form = response.data;
        this.daterangeTime[0] = this.form.dateStart;
        this.daterangeTime[1] = this.form.dateEnd;
        this.vacationOptions = response.vacations;
        this.open = true;
        this.title = "修改请假记录";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          //写入对应的人员日期信息
          this.form.ofcmpayId = this.monthofcInfo.ofcmpayId;
          this.form.userName = this.monthofcInfo.userName;
          this.form.userNick = this.monthofcInfo.userNick;
          this.form.ofcmpayYear = this.monthofcInfo.ofcmpayYear;
          this.form.ofcmpayMonth = this.monthofcInfo.ofcmpayMonth;

          if (this.form.leaveRecordId != null) {
            updateLeaverecord(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addLeaverecord(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const leaveRecordIds = row.leaveRecordId || this.ids;
      this.$modal.confirm('是否确认删除请假记录编号为"' + leaveRecordIds + '"的数据项？').then(function() {
        return delLeaverecord(leaveRecordIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    handleSetDate(){
      if (null != this.daterangeTime && '' != this.daterangeTime) {
        this.form.dateStart = this.daterangeTime[0];
        this.form.dateEnd = this.daterangeTime[1];
        let leaveDay = new Date(this.form.dateEnd).getTime() - new Date(this.form.dateStart).getTime();
        this.form.leaveDay = leaveDay/(3600 * 1000 * 24)
        this.handleCountVacationPay();
      }
    },
    handleCountVacationPay() {
      if(this.form.leaveDay!="" && this.form.leaveDay!=null && this.form.vacationId!="" && this.form.vacationId!=null){
        let item = this.vacationOptions.find(item => item.vacationId === this.form.vacationId);
        if(item!=null){
          // 基础薪资*请假天数*天数比例/满勤天数
          if(this.form.leaveDay>this.monthofcInfo.fullDay){
            this.form.leaveDay = this.monthofcInfo.fullDay
          }
          let pay = item.vacationWages * this.form.leaveDay * (item.vacationDp/100)/this.monthofcInfo.fullDay;
          this.form.vacationPay = Math.round(pay*100)/100;
        }
      }
    },
    validateRange() {
      return (rule, value, callback) => {
        if (null != this.daterangeTime && '' != this.daterangeTime) {
          callback()
        }else{
           return callback(new Error(`请假时间不能为空`))
        }
      }
    },
    // 返回按钮
    handleClose() {
      const obj = { path: "/ofcpay/monthofc" };
      this.$tab.closeOpenPage(obj);
    },
  }
};
</script>
